/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

Ext.QuickTips.init();
var _pageSize = 20;

var fieldName = ['id', 'loginName',  'employeeNo', 'realName', 'sex', 'age', 'phoneNo', 'email', 'note', 'status', 'orgCode', "deptId", 'updateTime', 'createTime', 'orgName', 'deptName',"priority","priorityName","invalidDate"];
var fieldLabel = ['ID', '用户名', '工号', '名字', '性别', '年龄', '电话', '邮箱', '备注', '状态', '单位', '部门', '更新时间', '创建时间'];
var fieldType = [];

var saveServlet = '../../servlet/system/UserSave';
var loadServlet = '../../servlet/system/UserLoad';
var deleteServlet = '../../servlet/system/UserDel';
var loadUserRoleServlet = '../../servlet/system/UserRoleLoad';
var saveUserRoleServlet = '../../servlet/system/UserRoleSave';
var resetPasswordServlet ='../../servlet/system/PwdReset';
var dbtable = 't_user';
var theme = '用户';

var _title = currentOrgName + theme + '管理';
//var _title = theme+'管理';


var deptStore = new Ext.data.JsonStore({
    url: '../../servlet/common/SimpleInfoLoad',
    baseParams: {id: 'id', name: 'name', tableName: 't_dept', orgCode: currentOrgCode},
    autoLoad: true,
    root: 'data',
    fields: ['id', 'name']
});

var deptCombo = {
    hiddenName: fieldName[12],
    fieldLabel: fieldLabel[12],
    id: 'DeptCombo',
    xtype: 'combo',
    width: 150,
    emptyText: '请选择部门...',
    loadingText: '正在加载部门信息',
    //queryDelay:300,
    editable: false,
    triggerAction: 'all',
    store: deptStore,
    displayField: 'name',
    valueField: 'id',
    mode: 'remote',
    allowBlank: true
};

//性别
var sexStore = new Ext.data.SimpleStore({
    fields: ['sex'],
    data: [['男'], ['女']]
});

//优先级
var priorityStore = new Ext.data.SimpleStore({
    fields: ['id','priority'],
    data: [[0,'低'], [1,'高']]
});

var inputForm = new Ext.FormPanel(
        {
            xtype: 'form',
            id: 'input-form',
            bodyStyle: 'padding:15px;background:transparent',
            frame: true,
            border: false,
            url: saveServlet,
            items: [{
                    name: fieldName[0],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[0],
                    hidden: true
                }, {
                    name: fieldName[1],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[1],
                    allowBlank: false,
                    blankText: '必须填写',
                    maxLength: 10,
                    maxLengthText: '不能多于10个字符,1个汉字占用2个字符'
                           
                },  {
                    name: fieldName[3],
                    id: fieldName[3],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[3],
                    allowBlank: true,
                    maxLength: 10,
                    maxLengthText: '不能多于10个字符,1个汉字占用2个字符'
                }, {
                    name: fieldName[4],
                    id: fieldName[4],
                    xtype: 'combo',
                    fieldLabel: fieldLabel[4],
                    width: 125,
                    triggerAction: 'all',
                    emptyText: '请选择性别...',
                    value: '男',
                    hiddenName: 'sex',
                    editable: false,
                    store: sexStore,
                    displayField: 'sex',
                    valueField: 'sex',
                    mode: 'local'

                }, {
                    name: fieldName[5],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[5],
                    allowBlank: true
                }, {
                    name: fieldName[6],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[6],
                    width: 150,
                    allowBlank: true,
                    maxLength: 10,
                    maxLengthText: '不能多于10个字符,1个汉字占用2个字符'
                }, {
                    //邮箱
                    name: fieldName[7],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[7],
                    //mail regex
                    regex: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
                    regexText: '邮箱格式不正确',
                    allowBlank: true,
                    width: 150,
                    maxLength: 50,
                    maxLengthText: '不能多于50个字符,1个汉字占用2个字符'
                }, {
                    name: fieldName[8],
                    xtype: 'textfield',
                    fieldLabel: fieldLabel[8],
                    allowBlank: true,
                    width: 150,
                    maxLength: 25,
                    maxLengthText: '不能多于25个字符,1个汉字占用2个字符'
                }, 
                {
                    name: "priority",
                    id: "Priority",
                    xtype: 'combo',
                    fieldLabel: "优先级",
                    width: 125,
                    triggerAction: 'all',
                    emptyText: '请选择优先级...',
                    value: 1,
                    hiddenName: 'priority',
                    editable: false,
                    store: priorityStore,
                    displayField: 'priority',
                    valueField: 'id',
                    mode: 'local'
                },
                {
                    xtype: 'textfield',
                    fieldLabel: "所属单位",
                    width: 150,
                    value: currentOrgName,
                    readOnly: true                    
                }
            ],
            buttons: [{
                    text: '保存',
                    iconCls: 'icon-save',
                    handler: function() {
                        var submitConfig = {
                            success: function(form, action) {
                                store.reload();
                                win.hide();
                            },
                            failure: function(form, action) {
                                switch (action.failureType) {
                                    case Ext.form.Action.CONNECT_FAILURE:
                                        Ext.Msg.alert('提示', '网络连接失败');
                                        break;
                                    case Ext.form.Action.SERVER_INVALID:
                                        Ext.Msg.alert('提示', action.result.msg);
                                }
                            },
                            params: {}
                        };
                        var token1 = new Date().getTime(); 
                        submitConfig.params.token=token;
                        submitConfig.params.token1=token1;
                        if (type === 1)
                            submitConfig.params.cmd = 'create';
                        else {
                            //submitConfig.params.id = checkboxSel.getSelected().get("id");
                            submitConfig.params.cmd = 'update';
                        }
                        Ext.getCmp('input-form').getForm().submit(submitConfig);

                    }
                }, {
                    text: '取消',
                    handler: function() {
                        win.hide();
                    }
                }]
        }
);
var win = new Ext.Window({
    layout: 'form',
    width: 340,
    autoHeight: true,
    closeAction: 'hide',
    modal: true,
    items: [inputForm]
});
var type = 1;         //判断打开窗口是进行更新，还是新建。1-新建；2-修改
var updated = false;
function addnew() {
    if (win === null) {
        win = new Ext.Window({
            layout: 'form',
            width: 340,
            autoHeight: true,
            closeAction: 'hide',
            items: [inputForm]
        });
    }
    type = 1;
    win.setTitle('增加' + theme);
    //if (updated)
    // Ext.getCmp('addusr-form').getForm().getEl().dom.reset();
    Ext.getCmp('input-form').getForm().reset();
    //Ext.getCmp(fieldName[11]).setValue(currentOrgCode);
    win.show();
    //loginForm.form.reset();

    //Ext.getCmp('code').enable();    
}

function update() {
    updated = true;
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
    }
    else if (checkboxSel.getSelections().length > 1) {
        Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
    }
    else {
        if (win === null) {
            win = new Ext.Window({
                layout: 'form',
                width: 340,
                autoHeight: true,
                closeAction: 'hide',
                items: [inputForm]
            });
        }

        //alert(checkboxSel.getSelected().get('code'));
        type = 2;
        Ext.getCmp('input-form').getForm().loadRecord(checkboxSel.getSelected());
        //Ext.Msg.alert("a",Ext.getCmp("code"));
        //Ext.getCmp('code').readOnly=true;
        //Ext.getCmp('YesNo').setValue(checkboxSel.getSelected().get("ismine"));

        //alert(str);
        //alert(Ext.getCmp('checkdate'));


        win.setTitle('修改' + theme);
        win.show();
        //Ext.getDom('win-title').innerHTML='修改监控设备信息';
    }
}

function remove() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("修改" + theme, "您还没有选择，需要先选择才能删除");
    }
    else {
        Ext.MessageBox.confirm('提示', '确实要删除所选的记录吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteServlet, //提交的删除地址
                    params: {token:token,token1:token1,ids: jsonData},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "所选记录成功删除！");
                                store.reload(); //重新load数据   	
                                //parent.Ext.getCmp('OrganTree').getNodeById(currentOrgCode).reload();
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "所选记录删除失败！");
                        }
                    }
                });
            }
        });
    }
}

function resetPassword() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能重置密码");
    }
    else {
        Ext.MessageBox.confirm('系统提示', '确实要重置所选用户的密码吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: resetPasswordServlet,
                    params: {token:token,token1:token1,ids: jsonData},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("系统提示", "所选用户密码已重置！");

                            }
                            else {
                                Ext.Msg.alert('系统提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("系统提示", "重置密码失败！");
                        }
                    }
                });
            }
        });
    }
}

function lockUser() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能操作");
    }
    else {
        Ext.MessageBox.confirm('系统提示', '确实要锁定所有选择的用户吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var conn = new Ext.data.Connection();
                var token1 = new Date().getTime();
                conn.request({
                    url: saveServlet,
                    params: {token:token,token1:token1,ids: jsonData, cmd: "lock"},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                store.reload();
                                Ext.MessageBox.alert("系统提示", "所选用户已锁定！");                                
                            }
                            else {
                                Ext.Msg.alert('系统提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("系统提示", "锁定失败！");
                        }
                    }
                });
            }
        });
    }
}

function unlockUser() {
    if (checkboxSel.getSelections().length === 0) {
        Ext.Msg.alert("系统提示", "您还没有选择，需要先选择才能操作");
    }
    else {
        Ext.MessageBox.confirm('系统提示', '确实要解锁所有选择的用户吗?', function(btn) {
            if (btn === 'yes') {
                var records = checkboxSel.getSelections();
                var jsonData = "";
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }
                var token1 = new Date().getTime();
                var conn = new Ext.data.Connection();
                conn.request({
                    url: saveServlet,
                    params: {token:token,token1:token1,ids: jsonData, cmd: "unlock"},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                store.reload();
                                Ext.MessageBox.alert("系统提示", "所选用户已解锁！");                                
                            }
                            else {
                                Ext.Msg.alert('系统提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("系统提示", "解锁失败！");
                        }
                    }
                });
            }
        });
    }
}

//用户已有的角色
var roleStore = new Ext.data.JsonStore({
    url: loadUserRoleServlet,
    fields: ['id', 'name', 'note', 'checked'],
    root: 'data',
    baseParams: {}
    //autoLoad:true 
});
var checkboxSelRole = new Ext.grid.CheckboxSelectionModel({checkOnly: true});
var roleGrid = new Ext.grid.GridPanel({
    store: roleStore,
    sm: checkboxSelRole,
    //autoHeight: true,
    height: 350,
    //disableSelection:true,
    columns: [
        checkboxSelRole,
        {header: 'id', dataIndex: 'id'},
        {header: '角色', sortable: true, dataIndex: 'name'
        },
        {header: '备注', sortable: true, dataIndex: 'note'},
        {header: 'checked', dataIndex: 'checked',
            renderer: function(value, metaData, record, rowIndex, colIndex, store) {
                var checked = record.get('checked');
                //alert(""+rowIndex+checked);
                //checkboxSelRole.selectRecords([record], checked);
                if (checked) {
                    checkboxSelRole.selectRow(rowIndex, true);
                } else {
                    checkboxSelRole.deselectRow(rowIndex);
                }
                return record.get('checked');
            }
        }
    ]});

var roleWin = new Ext.Window({
    title: '设置用户角色',
    id: 'RoleWin',
    width: 400,
    height: 350,
    modal: true,
    autoHeight: true,
    resizable: true,
    layout: 'fit',
    closable: true,
    closeAction: 'hide',
    items: [roleGrid],
    buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: function() {
                // 得到页面复选框 选的角色  提交   ////////////////////////////////////
                var records = checkboxSelRole.getSelections();
                var jsonData = '';
                for (var i = 0, len = records.length; i < len; i++) {
                    var ss = records[i].get("id"); //这里为Grid数据源的Id列
                    if (i === 0)
                        jsonData = jsonData + ss;
                    else
                        jsonData = jsonData + "," + ss;
                }

                var conn = new Ext.data.Connection();
                var token1 = new Date().getTime();
                conn.request({
                    url: saveUserRoleServlet,
                    params: {token:token,token1:token1,userId: roleStore.baseParams.userId, userRoles: jsonData},
                    method: 'post',
                    scope: this,
                    callback: function(options, success, response) {
                        checkboxSelRole.clearSelections();
                        roleWin.hide();
                        if (success) {
                            var messager = Ext.decode(response.responseText);
                            if (messager.success) {
                                Ext.MessageBox.alert("提示", "保存成功");
                            }
                            else {
                                Ext.Msg.alert('提示', messager.msg);
                            }

                        } else {
                            Ext.MessageBox.alert("提示", "保存失败！");
                        }
                    }
                });
            }
        }, {
            text: '重置',
            handler: function() {
                roleStore.reload();
            }
        }, {
            text: '取消',
            handler: function() {
                checkboxSelRole.clearSelections();
                roleWin.hide();

            }
        }]
});

function allocation() {
    if (roleWin !== null) {
        if (checkboxSel.getSelections().length === 0) {
            Ext.Msg.alert("提示", "您还没有选择，需要选择一个记录才能修改");
        }
        else if (checkboxSel.getSelections().length > 1) {
            Ext.Msg.alert("提示", "您选择了多个记录，只能选择一个记录进行修改");
        }
        else {
            var selected = checkboxSel.getSelected();
            var userId = selected.get("id");
            roleStore.baseParams.userId = userId;
            roleStore.reload();
            roleWin.show();
        }
    }
}


var checkboxSel = new Ext.grid.CheckboxSelectionModel();
var store;
function buildWindow() {


    store = new Ext.data.JsonStore({
        url: loadServlet,
        root: 'data',
        idProperty: 'id',
        totalProperty: 'count',
        fields: fieldName
                , baseParams: {start: 0, limit: _pageSize}
        , autoLoad: true,
        listeners:{
            exception:function(misc){
                Ext.Msg.alert("系统提示","Session超时，请重新登陆");
            }
        }        
    });

    var grid = new Ext.grid.GridPanel({
        title: _title,
        store: store,
        sm: checkboxSel,
        columns: [
            checkboxSel,
            {header: "状态", dataIndex: 'status', width: 40,
                renderer: function renderer(v, metaData, record, rowIndex, colIndex, store) {
                    var value = parseInt(v);
                    var imageName;
                    if (value === 9) {
                        imageName = 'lock.png';
                        return "<image src='" + basePath + "image/icon/" + imageName + "'/>";
                    } else
                        return "";
                }
            },
            {header: fieldLabel[0], sortable: true, dataIndex: fieldName[0], hidden: true},
            {header: fieldLabel[1], width: 80, sortable: true, dataIndex: fieldName[1]},
            //{header: fieldLabel[2], width: 80, sortable: true, dataIndex: fieldName[2]},
            {header: fieldLabel[3], width: 80, sortable: true, dataIndex: fieldName[3]},
            {header: fieldLabel[4], width: 50, sortable: true, dataIndex: fieldName[4]},
            {header: fieldLabel[5], width: 80, sortable: true, dataIndex: fieldName[5]},
            {header: fieldLabel[6], width: 50, sortable: true, dataIndex: fieldName[6]},
            {header: fieldLabel[7], width: 80, sortable: true, dataIndex: fieldName[7]},
            {header: fieldLabel[8], width: 100, sortable: true, dataIndex: fieldName[8]},
            {header: fieldLabel[9], width: 100, sortable: true, dataIndex: fieldName[9]},
            {header: fieldLabel[10], width: 100, sortable: true, dataIndex: fieldName[10], hidden: true},
            
            {header: "优先级", width: 80, sortable: true, dataIndex:"priorityName"},
            {header: "过期时间", width: 100, sortable: true, dataIndex:"invalidDate"},
            {header: fieldLabel[12], width: 100, sortable: true, dataIndex: fieldName[12], xtype: 'datecolumn', format: 'Y-m-d'},
            {header: fieldLabel[13], width: 100, sortable: true, dataIndex: fieldName[13], xtype: 'datecolumn', format: 'Y-m-d'}
        ],
        //autoExpandColumn: fieldName[2],
        //renderTo: Ext.getBody(),
        //width: 780,
        //height: 590,
        loadMask: true,
        tbar: new Ext.Toolbar([
            {text: '新增', iconCls: 'icon-add', handler: addnew},
            {text: '修改', iconCls: 'icon-edit', handler: update},
            {text: '删除', iconCls: 'icon-delete', handler: remove},
            '-',
            {text: '用户角色分配', iconCls: 'icon-group', handler: allocation},
            {text: '密码重置', iconCls: 'icon-key', handler: resetPassword},
            '-',
            {
                text: '锁定',
                iconCls: 'icon-lock',
                //hidden:'true',
                handler: lockUser
                        , style: {marginLeft: '10px'}
            },
            {
                text: '解锁',
                iconCls: 'icon-unlock',
                handler: unlockUser
            }
        ]),
        bbar: new Ext.PagingToolbar({
            pageSize: _pageSize,
            store: store,
            displayInfo: true,
            displayMsg: '显示记录：{0} - {1}   总记录：{2}',
            emptyMsg: "目前没有" + theme + '信息'
        })
    });
    //grid.el.center();
    //store.load({params: {start: 0, limit: _pageSize}});

    var applicationUI = new Ext.Viewport({
        layout: "fit",
        items: [
            grid
        ]
    });
}
Ext.onReady(buildWindow);
